package org.example.c_0_005;

import org.junit.Test;

import java.util.ArrayList;

/**
 * 实现一个集合，具有add(T t); size();两个方法。
 * 创建两个线程，线程一：给这个集合添加十个属性。 线程二：在集合大小等于五时执行，执行完后线程一继续执行。
 */
public class T_Topic01 {
    volatile boolean flag = false; // 线程二运行的标识

    class MyList<T>{
        private ArrayList<T> arrayList;

        public MyList() {
            this.arrayList = new ArrayList<>();
        }

        public void add(T t){
            arrayList.add(t);
        }

        public int size(){
            return arrayList.size();
        }
    }

    @Test
    public void test(){
        Object lock = new Object(); // 锁的对象
//        boolean flag = false;
        MyList<Integer> myList = new MyList<>();
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    myList.add(i);
                    System.out.println("此时容器大小："+myList.size());
                    if (myList.size()==5){
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized(lock){
                if (myList.size()!=5){
                    flag = true;
                    try {
                        lock.wait();
                        System.out.println("t2执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.notify();
                    }
                }
            }
        });
        t2.start();
        while (!flag){
            Thread.yield();
        }
        t1.start();
        try {
            t2.join();
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
